package cc.telecomdigital.tdstock.Framework.UniqueItem;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.TelephonyManager;

public class PhoneIncomingCallListener extends BroadcastReceiver
{
	public enum PHONE_STATE { IDLE, BEING_USED }
	// For external usage
	public interface IPhoneIncomingCallListener
	{
		/** Report on/off for the current display status **/
		void PhoneIncomingCall_Response(PHONE_STATE iState);
	}

	private boolean					debugMode	 = false;
	private final String				LOG_TAG	 = "PhoneStateChangeListener";

	private Context					hostContext;
	private IPhoneIncomingCallListener	     interfaceReport;
	private PHONE_STATE                     phoneState;

	/** Create a Display On/Off Change Listener, Broadcast Receiver **/
	public PhoneIncomingCallListener(Context iHostContext,
			IPhoneIncomingCallListener iReportInterface)
	{
		if (debugMode)
			TDStockLog.d(LOG_TAG, "Create a New Receiver");

		hostContext = iHostContext;
		interfaceReport = iReportInterface;

		IntentFilter actionFilter;

		actionFilter = new IntentFilter();
		actionFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
		
		phoneState = GetCurPhoneState();
		/* Provide our first result */
		if (iReportInterface != null)
			iReportInterface.PhoneIncomingCall_Response(phoneState);
		
		// *** Very interesting, the one would not send
		hostContext.registerReceiver(this, actionFilter);
		if (debugMode)
			TDStockLog.d(LOG_TAG, "Register Receiver");		
		
	}
	/** Disable the current usage of the Broadcast receiver **/
	private void Disable()
	{
		hostContext.unregisterReceiver(this);
		if (debugMode)
			TDStockLog.d(LOG_TAG, "Unregister Receiver");
	}

	/** Dispose the object **/
	public void Dispose()
	{
		Disable();
		if (debugMode)
			TDStockLog.d(LOG_TAG, "Object has been free");
	}

	@Override
	public void onReceive(Context context, Intent iIntent)
	{
		if (debugMode)
			TDStockLog.i(LOG_TAG, "Action: "
					+ iIntent.getAction().toString());

		if (iIntent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED))
		{
			PHONE_STATE 	  state;

			state = GetCurPhoneState();
			if (state == phoneState)
				return;
			
			phoneState = state;
			if (interfaceReport != null)
				interfaceReport.PhoneIncomingCall_Response(state);
			return;
		}
	}
	
	private PHONE_STATE GetCurPhoneState()
	{
		int              curState;
		TelephonyManager teleManager;			
		
		teleManager = (TelephonyManager) hostContext.getSystemService(Context.TELEPHONY_SERVICE);
		if (teleManager == null)
			return PHONE_STATE.IDLE;
	
		curState = teleManager.getCallState();
		if (curState == TelephonyManager.CALL_STATE_IDLE)
			return PHONE_STATE.IDLE;

		return PHONE_STATE.BEING_USED;		
	}

	/** Set DebugMessage Level **/
	public void SetDebugMode(boolean iEnable)
	{
		debugMode = iEnable;
	}
}
